from datetime import datetime
from typing import Dict, List
from sqlalchemy import distinct, outerjoin, select, update
from app.api.admin.model.coupon.coupon import CouponCateModel, CouponModel
from app.api.admin.model.order.order import OrderModel
from app.api.admin.schema.order.order import OrderListInSchema, OrderOutSchema
from app.dependencies.database import db
from fastapi_pagination.ext.databases import paginate
from fastapi_pagination import Params


class OrderService():
    async def list(self, list_in: OrderListInSchema):
        '''
        status：（1待使用2已核销3过期）
        '''
        print("list_in", list_in.model_dump())
        where = []
        if list_in.status != 0:
            where.append(OrderModel.status == list_in.status)
        if list_in.coupon_cate_id:
            where.append(CouponCateModel.id == list_in.coupon_cate_id)
        

        query = (select(
            OrderModel,
            CouponModel.name.label("coupon_name"),
            CouponModel.min_amount,
            CouponModel.discount_amount,
            CouponModel.min_amount,
            CouponModel.start_time,
            CouponModel.end_time,
            CouponCateModel.name.label("coupon_cate_name"),
        )
            .select_from(OrderModel)
            .outerjoin(CouponModel, CouponModel.id == OrderModel.coupon_id)
            .outerjoin(CouponCateModel, CouponCateModel.key == CouponModel.cate_id)
            .where(*where)

        )

        result = await paginate(db, query)
        # print("records", records.__dict__)
        print("records", result.total)

        # 判断订单是否过期
        for order in result.list:
            # print("order", order)
            # print("end_time", order.end_time, type(order.end_time))
            # print("now", datetime.now())
            # 已核销的不改变状态
            if order.status == 2 or order.status == 3:
                continue
            # print("order.end_time", order.end_time, type(order.end_time))
            if order.end_time <= datetime.now():
                order.status = 3
                # 修改状态
                await db.execute(update(OrderModel).where(OrderModel.id == order.id).values({"status": 3}))
            # await db.execute(update(CouponModel).where(CouponModel.id == order.coupon_id).values({"status": 3}))
        # 驼峰
        result.list = [item.model_dump(by_alias=True)
                       for item in result.list]
        return result

    async def cancel(self, order_id: str):
        return await db.execute(update(OrderModel).where(OrderModel.id == order_id).values({"status": 2}))

    async def detail(self, order_id: str):
        return await db.fetch_one(select(OrderModel).where(OrderModel.order_id == order_id))

    async def change_status(self, order_id: int, status: int):
        return await db.execute(update(OrderModel).where(OrderModel.id == id).values({"status": status}))

    @ classmethod
    async def instance(cls):
        return cls()
